package prv.pursuivant.util;

import java.util.BitSet;

/**
 * Class for escaping urls. It is used instead of URLEncoder because of escaping
 * space with plus character, which messed with Firefox. I prefer %20 notation
 * 
 * @author Kwinto
 * 
 */

public class URLUtil {

	static BitSet validChars = new BitSet(128);
	static {
		for (char c = 'a'; c <= 'z'; c++)
			validChars.set(c);
		for (char c = 'A'; c <= 'Z'; c++)
			validChars.set(c);
		for (char c = '0'; c <= '9'; c++)
			validChars.set(c);
		for (char c : "-_.!~*'()".toCharArray())
			validChars.set(c);
	}

	public String escape(String filename) {
		StringBuilder sb = new StringBuilder(filename.length());
		for (char c : filename.toCharArray()) {
			if (c > 0 && c < 128 && validChars.get(c))
				sb.append(c);
			else {
				sb.append('%');
				char c1 = Character.forDigit((c >> 4) & 0xf, 16);
				if (Character.isLetter(c1) && Character.isLowerCase(c1))
					c1 = Character.toUpperCase(c1);
				sb.append(c1);
				c1 = Character.forDigit(c & 0xf, 16);
				if (Character.isLetter(c1) && Character.isLowerCase(c1))
					c1 = Character.toUpperCase(c1);
				sb.append(c1);
			}
		}
		return sb.toString();
	}

}
